<template>
  <div class="address-book">
    <address-item avatar="/chat-new-friend.png" name="新的朋友" />
    <address-item avatar="/chat-only.png" name="仅聊天的朋友" />
    <address-item avatar="/chat-tag.png" name="标签" />
    <div v-for="(item, index) in result" :key="index">
        <div v-if="item.isSortName" class="sort-name">
            <span>{{ item.name }}</span>
        </div>
        <address-item v-else :avatar="item.avatar" :name="item.name"  />
    </div>
  </div>
</template>

<script>
import pinyin from "pinyin"
import { flat } from '../../util/flat'
import addressItem from "../../components/address-item.vue"
export default {
  components: { addressItem },
  name: "address-book",
  data() {
    return {
      address: [
        {
          avatar: "https://www.tsdy.club/blog/medias/avatar.jpg",
          name: "学霸",
        },
        {
          avatar: "https://www.tsdy.club/blog/medias/avatar.jpg",
          name: "马牛逼",
        },
        {
          avatar: "https://www.tsdy.club/blog/medias/avatar.jpg",
          name: "Tsdy",
        },
      ],
      result: [],
    };
  },
  created() {
    const result = {};
    this.address.forEach(item => {
        const arr = pinyin(item.name, {
            style: pinyin.STYLE_FIRST_LETTER
        })
        const first = arr[0][0][0].toLocaleLowerCase()
        if (!result[first]) {
            result[first] = [];
            result[first].push({
                isSortName: true,
                name: first
            })
        }
        result[first].push(item);
    });
    const array = Object.values(result);
    array.sort((a, b) => {
        return a[0].name.localeCompare(b[0].name)
    })
    this.result = flat(array);


  },
};
</script>

<style scoped>
.address {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}
.sort-name {
    height: 26px;
    width: 100%;
    background-color: rgb(244, 245, 246);
    display: flex;
}
.sort-name > span {
    margin: auto auto auto 6px;
    color: #bfb1b1;
}
</style>